<template>
  <view class="page-header">
    <view class="back-button" @click="goBack">‹ {{ $t('blueIndex.back') }}</view>
    <view class="device-title">{{ connectionStatusText }}</view>
  </view>
  <view class="device-container">
    <view class="content-box">
      <!-- BaseCharts 组件现在会在点击“开始监测”后立即显示一个带坐标轴的空图表 -->
      <template v-if="chartData.categories.length">
        <BaseCharts :option="chartOption" />
      </template>
      <template v-else>
        <view class="no-data-text">
          {{
            isMonitoring
              ? t('blueIndex.receivingData')
              : measurementCount === 0
              ? t('blueIndex.clickToMonitorLeft')
              : measurementCount === 1
              ? t('blueIndex.clickToMonitorRight')
              : t('blueIndex.allMeasurementsCompleted')
          }}
        </view>
      </template>
    </view>
    <view class="button-group">
      <button
        class="btn btn-blue"
        @tap="startMonitoring"
        :disabled="isConnecting || isMonitoring || measurementCount >= 2">
        {{
          isMonitoring
            ? currentMonitoringHand === 'left'
              ? t('blueIndex.monitoringLeft')
              : t('blueIndex.monitoringRight')
            : measurementCount === 0
            ? t('blueIndex.startMonitoringLeft')
            : measurementCount === 1
            ? t('blueIndex.startMonitoringRight')
            : t('blueIndex.allDone')
        }}
      </button>
      <button class="btn btn-red" @tap="stopMonitoring" :disabled="!isMonitoring">
        {{ t('blueIndex.stopMonitoring') }}
      </button>
      <button class="btn btn-orange" @tap="uploadDataToBackend" :disabled="measurementCount < 2 || isMonitoring">
        {{ t('blueIndex.viewResults') }}
      </button>
    </view>
  </view>
</template>

<script setup>
  import { ref, onUnmounted, reactive, computed, onMounted } from 'vue'
  import { useI18n } from 'vue-i18n'
  import BaseCharts from './BaseCharts.vue'
  import { pulse_diagnosis, getPulseDiagnosisResult } from '@/api/acupoint.js'
  import { bleStore } from '@/utils/ble-store' // Adjust the path if necessary
  // import VConsole from "vconsole";

  const { t } = useI18n()

  // --- 16进制数据解析器类 ---
  class BLEDataParser14Channel {
    constructor() {
      // 数据格式定义
      this.FRAME_DATA_COUNT = 14 // 12通道 + 气囊气压 + 电压
      this.DATA_BYTES_PER_CHANNEL = 2 // 每个数据2字节
      this.SEPARATOR_BYTE = 0x2c // 分隔符 ','
      this.BYTES_PER_FRAME = this.FRAME_DATA_COUNT * (this.DATA_BYTES_PER_CHANNEL + 1) // 42字节

      // 通道定义
      this.CHANNEL_NAMES = [
        '通道1',
        '通道2',
        '通道3',
        '通道4',
        '通道5',
        '通道6',
        '通道7',
        '通道8',
        '通道9',
        '通道10',
        '通道11',
        '通道12',
        '气囊气压',
        '电压'
      ]
    }

    // 解析蓝牙数据帧
    parseFrame(bytes) {
      const result = {
        success: false,
        error: null,
        data: null,
        hex: null,
        raw: bytes,
        timestamp: Date.now()
      }

      try {
        // 转换为16进制字符串用于调试
        result.hex = this.bytesToHexString(bytes)

        // 验证数据长度
        if (bytes.length !== this.BYTES_PER_FRAME) {
          result.error = `数据长度不正确，期望${this.BYTES_PER_FRAME}字节，实际${bytes.length}字节`
          return result
        }

        // 解析数据
        const parsedData = this.parseDataFrame(bytes)
        if (parsedData) {
          result.success = true
          result.data = parsedData
        } else {
          result.error = '数据解析失败'
        }
      } catch (error) {
        result.error = `解析异常: ${error.message}`
      }

      return result
    }

    // 解析数据帧内容
    parseDataFrame(bytes) {
      const data = {}
      let offset = 0

      try {
        // 解析12个通道数据 + 气囊气压 + 电压
        for (let i = 0; i < this.FRAME_DATA_COUNT; i++) {
          // 检查是否有足够的数据
          if (offset + this.DATA_BYTES_PER_CHANNEL + 1 > bytes.length) {
            throw new Error(`数据长度不足，无法解析第${i + 1}个数据`)
          }

          // 读取2字节数据（大端序）
          const dataBytes = bytes.slice(offset, offset + this.DATA_BYTES_PER_CHANNEL)
          const value = this.bytesToInt16BigEndian(dataBytes)

          // 读取分隔符
          const separator = bytes[offset + this.DATA_BYTES_PER_CHANNEL]

          // 验证分隔符
          if (separator !== this.SEPARATOR_BYTE) {
            // 分隔符不正确，但继续处理
          }

          // 存储数据
          const channelName = this.CHANNEL_NAMES[i]
          data[channelName] = {
            value: value,
            rawBytes: dataBytes,
            hexValue: this.bytesToHexString(dataBytes),
            separator: separator,
            index: i + 1
          }

          // 移动偏移量
          offset += this.DATA_BYTES_PER_CHANNEL + 1
        }

        return data
      } catch (error) {
        return null
      }
    }

    // 字节数组转16位整数（大端序）
    bytesToInt16BigEndian(bytes) {
      if (bytes.length !== 2) {
        throw new Error('需要2个字节来转换为16位整数')
      }

      // 大端序：高字节在前，低字节在后
      return (bytes[0] << 8) | bytes[1]
    }

    // 字节数组转16进制字符串
    bytesToHexString(bytes, separator = ' ') {
      return Array.from(bytes)
        .map(byte => byte.toString(16).padStart(2, '0').toUpperCase())
        .join(separator)
    }

    // 转换为原始字符串格式（用于向后兼容）
    convertToOriginalFormat(data) {
      if (!data) return ''

      // 构建类似原始格式的字符串
      const values = []
      for (let i = 1; i <= 12; i++) {
        const channelName = `通道${i}`
        if (data[channelName]) {
          values.push(data[channelName].value)
        } else {
          values.push(0)
        }
      }

      // 添加气囊气压和电压
      if (data['气囊气压']) {
        values.push(data['气囊气压'].value)
      } else {
        values.push(0)
      }

      if (data['电压']) {
        values.push(data['电压'].value)
      } else {
        values.push(0)
      }

      // 返回逗号分隔的字符串
      return values.join(',')
    }
  }

  // 创建数据解析器实例
  const dataParser = new BLEDataParser14Channel()

  // --- 状态定义 ---
  const isConnecting = ref(false)
  const isMonitoring = ref(false)
  const connectionStatus = ref('disconnected')
  const connectionStatusText = ref(t('blueIndex.statusUnconnected'))

  // --- WebBluetooth 状态定义 ---
  let connectedDevice = null
  let notifyCharacteristic = null
  let writeCharacteristic = null
  let dataBuffer = new Uint8Array(0) // 改为字节数组缓冲区
  const isReconnecting = ref(false)
  let reconnectAttempts = 0

  // --- BLE UUID 定义 ---
  const COMM_SERVICE_UUID = '0000fff0-0000-1000-8000-00805f9b34fb'
  const NOTIFY_CHARACTERISTIC_UUID = '0000fff1-0000-1000-8000-00805f9b34fb'
  const WRITE_CHARACTERISTIC_UUID = '0000fff2-0000-1000-8000-00805f9b34fb'

  // --- 左右手数据存储 ---
  const leftHandData = ref([])
  const rightHandData = ref([])
  const allReceivedData = ref([]) // 用于当前正在进行的测量
  const measurementCount = ref(0) // 0: 未开始, 1: 左手完成, 2: 右手完成
  const currentMonitoringHand = ref('') // 'left' 或 'right'

  // --- 图表和数据核心配置 ---
  const MONITORING_DURATION_SECONDS = 70 // 总监测时长（秒）
  const CHART_SAMPLE_INTERVAL = 1000 // 图表采样间隔（毫秒）
  const TOTAL_DATA_POINTS = (MONITORING_DURATION_SECONDS * 1000) / CHART_SAMPLE_INTERVAL // 计算X轴总点数

  const currentDataIndex = ref(0)

  let lastChartSampleTime = 0
  let initialDataTimeoutId = null

  const chartData = reactive({
    categories: [],
    seriesData: Array.from({ length: 3 }, () => [])
  })

  const chartOption = computed(() => {
    const series = [
      { name: t('blueIndex.legendCun'), type: 'line', smooth: true, showSymbol: false, data: chartData.seriesData[0] },
      { name: t('blueIndex.legendGuan'), type: 'line', smooth: true, showSymbol: false, data: chartData.seriesData[1] },
      { name: t('blueIndex.legendChi'), type: 'line', smooth: true, showSymbol: false, data: chartData.seriesData[2] }
    ]
    return {
      legend: { data: series.map(s => s.name), top: '5%', left: 'center' },
      grid: { left: '7%', right: '7%', bottom: '12%', top: '22%', containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: chartData.categories,
        axisLine: { show: true }, // 显示坐标轴线
        axisTick: { show: false }, // 不显示刻度线
        axisLabel: { show: false } // 不显示刻度数字
      },
      yAxis: [
        {
          type: 'value',
          name: '',
          position: 'left',
          axisLine: { show: false },
          axisTick: { show: false },
          min: 0,
          max: 5000,
          interval: 1000,
          splitLine: { show: true, lineStyle: { type: 'dashed' } } // 显示虚线分割线
        }
      ],
      series: series,
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          animation: false
        }
      }
    }
  })

  function debounce(func, delay) {
    let timeout
    const debounced = function (...args) {
      clearTimeout(timeout)
      timeout = setTimeout(() => {
        func.apply(this, args)
      }, delay)
    }
    debounced.cancel = function () {
      clearTimeout(timeout)
    }
    return debounced
  }

  const debouncedStopMonitoring = debounce(() => {
    // 根据当前测量次数给出不同的提示
    if (measurementCount.value === 0) {
      // 第一次测量完成
      uni.showToast({ title: t('blueIndex.leftHandDataFinished'), icon: 'none' })
      stopMonitoring(false) // 不显示停止提示，直接进入下一步引导
    } else if (measurementCount.value === 1) {
      // 第二次测量完成
      uni.showToast({ title: t('blueIndex.rightHandDataFinished'), icon: 'none' })
      stopMonitoring(false) // 不显示停止提示
    } else {
      uni.showToast({ title: t('blueIndex.dataTransferFinished'), icon: 'none' })
      stopMonitoring(true) // 显示停止提示
    }
  }, 2000)

  const initChartData = () => {
    console.log(`初始化图表，总点数: ${TOTAL_DATA_POINTS}`)
    currentDataIndex.value = 0
    chartData.categories = Array.from({ length: TOTAL_DATA_POINTS }, (_, i) => i)
    chartData.seriesData.forEach((series, index) => {
      chartData.seriesData[index] = new Array(TOTAL_DATA_POINTS).fill(null)
    })
  }

  const stringToArrayBuffer = str => {
    const buf = new ArrayBuffer(str.length)
    const bufView = new Uint8Array(buf)
    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i)
    }
    return buf
  }

  // const dataViewToString = dataView => new TextDecoder().decode(dataView) // 未使用

  const startMonitoring = async () => {
    if (isMonitoring.value) return
    if (measurementCount.value >= 2) {
      uni.showToast({ title: t('blueIndex.allMeasurementsCompleted'), icon: 'none' })
      return
    }

    if (!connectedDevice) {
      uni.showToast({ title: t('blueIndex.deviceNotConnected'), icon: 'none' })
      return
    }

    isConnecting.value = true
    initChartData()
    allReceivedData.value = [] // 重置当前测量的数据缓冲区
    dataBuffer = new Uint8Array(0) // 重置字节缓冲区
    lastChartSampleTime = 0

    // 确定当前是左手还是右手测量
    currentMonitoringHand.value = measurementCount.value === 0 ? 'left' : 'right'
    uni.showToast({
      title:
        currentMonitoringHand.value === 'left'
          ? t('blueIndex.startMonitoringLeft')
          : t('blueIndex.startMonitoringRight'),
      icon: 'none'
    })

    try {
      if (!writeCharacteristic) {
        const server = connectedDevice.gatt
        const service = await server.getPrimaryService(COMM_SERVICE_UUID)
        notifyCharacteristic = await service.getCharacteristic(NOTIFY_CHARACTERISTIC_UUID)
        writeCharacteristic = await service.getCharacteristic(WRITE_CHARACTERISTIC_UUID)
      }

      await notifyCharacteristic.startNotifications()
      notifyCharacteristic.addEventListener('characteristicvaluechanged', handleCharacteristicValueChanged)

      const startCommand = 'mode=3\r\n'
      await writeCharacteristic.writeValueWithoutResponse(stringToArrayBuffer(startCommand))

      isMonitoring.value = true
      initialDataTimeoutId = setTimeout(() => {
        if (isMonitoring.value) {
          console.error('启动后8秒内未收到任何数据，自动停止监测。')
          uni.showToast({ title: t('blueIndex.deviceNoResponse'), icon: 'none' })
          stopMonitoring(true)
        }
      }, 8000)
    } catch (error) {
      uni.showToast({ title: t('blueIndex.operationFailed', { message: error.message }), icon: 'none' })
      console.error('启动监测失败:', error)
    } finally {
      isConnecting.value = false
    }
  }

  const stopMonitoring = async (showAlert = true) => {
    if (!isMonitoring.value) {
      return
    }

    if (initialDataTimeoutId) {
      clearTimeout(initialDataTimeoutId)
      initialDataTimeoutId = null
    }
    debouncedStopMonitoring.cancel()

    isMonitoring.value = false

    try {
      if (notifyCharacteristic) {
        notifyCharacteristic.removeEventListener('characteristicvaluechanged', handleCharacteristicValueChanged)
        await notifyCharacteristic.stopNotifications()
      }

      if (writeCharacteristic && connectedDevice && connectedDevice.gatt.connected) {
        const stopCommand = 'mode=0\r\n'
        await writeCharacteristic.writeValueWithoutResponse(stringToArrayBuffer(stopCommand))
      }

      // 存储数据并更新测量次数
      if (currentMonitoringHand.value === 'left') {
        leftHandData.value = [...allReceivedData.value]
        measurementCount.value = 1
        if (showAlert) {
          uni.showToast({ title: t('blueIndex.leftHandMeasurementComplete'), icon: 'success' })
        }
        // 提示用户开始右手测量
        setTimeout(() => {
          uni.showModal({
            title: t('blueIndex.nextStep'),
            content: t('blueIndex.promptStartRightHand'),
            showCancel: false,
            confirmText: t('blueIndex.ok')
          })
        }, 500)
      } else if (currentMonitoringHand.value === 'right') {
        rightHandData.value = [...allReceivedData.value]
        measurementCount.value = 2
        if (showAlert) {
          uni.showToast({ title: t('blueIndex.rightHandMeasurementComplete'), icon: 'success' })
        }
        // 提示用户可以查看结果了
        setTimeout(() => {
          uni.showModal({
            title: t('blueIndex.allComplete'),
            content: t('blueIndex.promptViewResults'),
            showCancel: false,
            confirmText: t('blueIndex.ok')
          })
        }, 500)
      }
      currentMonitoringHand.value = '' // 重置当前监测的手
    } catch (error) {
      console.error('停止监测过程中发生错误:', error)
      uni.showToast({ title: t('blueIndex.stopFailed', { message: error.message }), icon: 'none' })
    }
  }

  const handleCharacteristicValueChanged = event => {
    const value = event.target.value
    if (initialDataTimeoutId) {
      clearTimeout(initialDataTimeoutId)
      initialDataTimeoutId = null
    }

    // 获取字节数据
    const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength)

    // 合并到缓冲区
    const newBuffer = new Uint8Array(dataBuffer.length + bytes.length)
    newBuffer.set(dataBuffer)
    newBuffer.set(bytes, dataBuffer.length)
    dataBuffer = newBuffer

    // 处理完整的数据帧
    while (dataBuffer.length >= dataParser.BYTES_PER_FRAME) {
      const frameBytes = dataBuffer.slice(0, dataParser.BYTES_PER_FRAME)
      const result = dataParser.parseFrame(frameBytes)

      if (result.success) {
        // 转换为原始字符串格式用于存储
        const lineString = dataParser.convertToOriginalFormat(result.data)
        allReceivedData.value.push(lineString)

        // 处理图表数据（取前3个通道）
        const values = [
          result.data['通道1']?.value || 0,
          result.data['通道4']?.value || 0,
          result.data['通道7']?.value || 0
        ]

        // 验证数据范围（16位数据范围：0-65535）
        const MAX_AD_VALUE = 65535
        if (values.some(v => v < 0 || v > MAX_AD_VALUE)) {
          console.warn(`[数据警告] 数据值超出16位范围 (0-${MAX_AD_VALUE})。值: ${values.join(', ')}`)
        }

        const now = Date.now()
        if (now - lastChartSampleTime > CHART_SAMPLE_INTERVAL) {
          lastChartSampleTime = now
          processAndDisplayData(values)
        }
      } else {
        console.warn(`[数据丢弃] 解析失败: ${result.error}`)
        console.warn(`原始数据: ${dataParser.bytesToHexString(frameBytes)}`)
      }

      // 移除已处理的数据帧
      dataBuffer = dataBuffer.slice(dataParser.BYTES_PER_FRAME)
    }

    debouncedStopMonitoring()
  }

  const uploadDataToBackend = async () => {
    if (measurementCount.value < 2) {
      uni.showToast({ title: t('blueIndex.completeBothHands'), icon: 'none' })
      return
    }
    if (isMonitoring.value) {
      uni.showToast({ title: t('blueIndex.stopBeforeUpload'), icon: 'none' })
      return
    }

    const payload = {
      deviceId: connectedDevice?.id || 'unknown_device',
      timestamp: new Date().toISOString(),
      left_data: leftHandData.value, // 左手数据
      right_data: rightHandData.value // 右手数据
    }

    console.log(`准备上传左右手数据到后端...`)
    console.log(`左手数据条数: ${payload.left_data.length}`)
    console.log(`右手数据条数: ${payload.right_data.length}`)
    uni.showLoading({ title: t('blueIndex.uploading') })

    try {
      // 调用新的接口格式
      const res = await pulse_diagnosis({
        left_data: payload.left_data,
        right_data: payload.right_data
      })

      uni.hideLoading()

      if (res.code === 200) {
        uni.showToast({ title: t('blueIndex.uploadSuccess'), icon: 'success' })
        if (res.result && (res.result.left_status == '000' || res.result.right_status === '000')) {
          uni.navigateTo({
            url: `/pages/blue/PulseAnalysis?appointNo=${res.result.appoint_no}`
          })
        } else {
          uni.showToast({ title: '请重新检测', icon: 'none' })
        }
      } else {
        throw new Error(`HTTP 错误 ${res.statusCode} 或 ${res.msg}`)
      }
    } catch (error) {
      uni.hideLoading()
      uni.showToast({ title: t('blueIndex.errorInfo'), icon: 'none' })
      console.error('上传数据到后端失败:', error)
    }
  }

  const processAndDisplayData = values => {
    const idx = currentDataIndex.value

    if (idx >= TOTAL_DATA_POINTS) {
      console.warn(`数据点索引 (${idx}) 已超出图表总点数 (${TOTAL_DATA_POINTS})。不再更新图表。`)
      return
    }

    const sensorVals = values

    for (let i = 0; i < 3; i++) {
      chartData.seriesData[i][idx] = sensorVals[i]
    }

    currentDataIndex.value++
  }

  const closeBLEConnection = async () => {
    if (connectedDevice && connectedDevice.gatt.connected) {
      if (notifyCharacteristic) {
        try {
          notifyCharacteristic.removeEventListener('characteristicvaluechanged', handleCharacteristicValueChanged)
          await notifyCharacteristic.stopNotifications()
        } catch (e) {
          console.warn('在断开连接时停止通知失败 (可能已断开):', e.message)
        }
      }
      connectedDevice.removeEventListener('gattserverdisconnected', onDisconnected)
      await connectedDevice.gatt.disconnect()
    }
    resetBluetoothState()
  }

  const onDisconnected = () => {
    if (!isMonitoring.value) {
      resetBluetoothState()
      return
    }

    debouncedStopMonitoring.cancel()
    uni.showToast({ title: t('blueIndex.connectionInterrupted'), icon: 'none' })

    if (notifyCharacteristic) {
      notifyCharacteristic.removeEventListener('characteristicvaluechanged', handleCharacteristicValueChanged)
    }
    resetBluetoothState()
    connectionStatus.value = 'error'
    connectionStatusText.value = t('blueIndex.statusInterrupted')
  }

  function goBack() {
    if (isMonitoring.value) {
      uni.showModal({
        title: t('blueIndex.goBackPromptTitle'),
        content: t('blueIndex.goBackPromptContent'),
        success: async res => {
          if (res.confirm) {
            await stopMonitoring(true) // 停止并显示提示
            backfn()
          }
        }
      })
    } else {
      backfn()
    }
  }

  function backfn() {
    const pages = getCurrentPages()
    if (pages.length > 1) {
      uni.navigateBack({ delta: 1 })
    } else {
      uni.reLaunch({ url: '/pages/index/index' })
    }
  }

  const resetBluetoothState = () => {
    isConnecting.value = false
    isMonitoring.value = false
    isReconnecting.value = false
    reconnectAttempts = 0
    connectionStatus.value = 'disconnected'
    connectionStatusText.value = t('blueIndex.statusUnconnected')
    connectedDevice = null
    notifyCharacteristic = null
    writeCharacteristic = null
    dataBuffer = new Uint8Array(0) // 重置字节缓冲区

    // 重置测量状态，但不清空已测完的左右手数据，因为用户可能需要重新上传
    // 如果需要彻底清空，可以 uncomment 下面两行
    // leftHandData.value = []
    // rightHandData.value = []
    // measurementCount.value = 0
    // currentMonitoringHand.value = ''
  }

  onMounted(() => {
    uni.setNavigationBarTitle({
      title: t('blueIndex.title')
    })
    //new VConsole(); // 如果需要调试，可以取消注释

    const device = bleStore.getActiveDevice()
    if (!device || !device.gatt.connected) {
      uni.showToast({ title: t('blueIndex.connectDeviceInList'), icon: 'none' })
      // setTimeout(() => { // 如果需要自动返回，可以取消注释
      //   goBack();
      // }, 3000);
      return
    }
    connectedDevice = device
    connectionStatusText.value = t('blueIndex.statusConnected', { deviceName: connectedDevice.name })
    connectedDevice.addEventListener('gattserverdisconnected', onDisconnected)
  })

  onUnmounted(async () => {
    isMonitoring.value = false
    debouncedStopMonitoring.cancel()
    clearTimeout(initialDataTimeoutId)
    initialDataTimeoutId = null
    await closeBLEConnection()
  })
</script>

<style lang="scss" scoped>
  // Page container styles to match the image
  page {
    background-color: #f0f0f0;
  }

  .device-container {
    display: flex;
    flex-direction: column;
    height: 60vh;
    background-color: #f0f0f0; // Light gray background from image
    padding: 0 40rpx 40rpx 40rpx;
    margin-top: 20px;
    box-sizing: border-box;
  }

  .content-box {
    flex-grow: 1;
    background-color: #ffffff;
    border-radius: 12rpx;
    margin-bottom: 40rpx;
    width: 100%;
    height: 400rpx; // 👈 加上这个：设置图表区域高度
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  // Placeholder for the header shown in the image (back arrow + title)
  .header-placeholder {
    flex-shrink: 0;
    padding: 20rpx 0;
    display: flex;
    align-items: center;
    position: relative;
    height: 88rpx; // Common header height

    .back-arrow {
      font-size: 40rpx;
      font-weight: bold;
      color: #333;
    }

    .page-title {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      font-size: 36rpx;
      color: #000;
    }
  }

  // This is the main white box area
  .content-box {
    flex-grow: 1;
    background-color: #ffffff;
    border-radius: 12rpx;
    margin-bottom: 40rpx;
    width: 100%;
  }

  // Button container styles
  .button-group {
    display: flex;
    justify-content: space-between;
    gap: 20rpx;
    flex-shrink: 0;
    width: 100%;
    flex-wrap: wrap; // 允许按钮换行

    .btn {
      flex: 1;
      min-width: 200rpx; // 确保按钮不会太窄
      margin: 10rpx 0; // 调整外边距以适应换行
      padding: 20rpx 0;
      border-radius: 12rpx;
      font-size: 28rpx;
      color: white;
      border: none;

      // Remove default button styles
      &::after {
        border: none;
      }

      &:disabled {
        opacity: 0.5;
      }
    }

    .btn-blue {
      background-color: #3c82f6;
    }

    .btn-red {
      background-color: #eb4d4b;
    }

    .btn-orange {
      background-color: #f39c12;
    }

    .btn-purple {
      background-color: #8a2be2;
    }

    .btn-green {
      background-color: #28a745;
    }
  }

  .no-data-text {
    color: #999;
    font-size: 28rpx;
    text-align: center;
  }

  .page-header {
    display: flex;
    align-items: center;
    padding: 20rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;
  }

  .back-button {
    font-size: 32rpx;
    color: #007aff;
    cursor: pointer;
  }

  .device-title {
    flex-grow: 1;
    text-align: center;
    font-size: 34rpx;
    font-weight: 700;
    margin-right: 80rpx;
  }

  page {
    background-color: #f0f0f0;
  }
</style>
